<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!--表格 -->
      <tree-table :data="catelist" :columns="columns" :selection-type='false' :expand-type="false" :show-index='true'
        index-text="#" border :show-row-hover="false" class="treeTable">
        <!--是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color:lightgreen;font-size:16px"></i>
          <i class="el-icon-error" v-else style="color:red;font-size:16px"></i>
        </template>
        <template slot-scope="scope" slot="order">
          <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditCateDialog(scope.row)">编辑
          </el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCate(scope.row)">删除</el-button>
        </template>
      </tree-table>

      <!--分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[3, 5, 15, 20]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!--添加商品分类的Dialog -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogVisible" width="50%" @close="addCateDialogClosed">
      <el-form ref="addCateFormRef" label-width="90px" :model="addCateForm" :rules="addCateFormRules">
        <!-- 分类名称 -->
        <el-form-item label="分类名称: " prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <!--父级分类 也就是1 2级-->
        <el-form-item label="父级分类: " prop="cat_name">
          <!-- props用来指定配置对象 options是数据源-->
          <el-cascader :options="parentCateList" expandTrigger='hover' :props="cascaderProps" v-model="selectedKeys"
            @change="parentCateChanged" clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!--根据id修改商品分类 -->
    <el-dialog title="编辑商品分类名称" :visible.sync="editCateDialogVisible" width="50%" @close="editCateDialogClosed">
      <el-form ref="editCateFormRef" label-width="90px" :model="editCateForm" :rules="addCateFormRules">
        <!-- 分类名称 -->
        <el-form-item label="分类名称: " prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        //  商品分类的数据
        catelist: [],
        // 查询条件
        queryInfo: {
          type: 3,
          pagenum: 1,
          pagesize: 5
        },
        // 总条数
        total: 0,
        // 为table指定列的定义
        columns: [{
            label: '分类名称',
            prop: 'cat_name'
          },
          {
            label: '是否有效',
            // 表示当前列定义为模板列
            type: 'template',
            // 表示当前列所使用的模板名
            template: 'isok'
          },
          {
            label: '排序',
            type: 'template',
            template: 'order'
          },
          {
            label: '操作',
            type: 'template',
            template: 'opt'
          }
        ],
        // 控制分类添加的显示与隐藏
        addCateDialogVisible: false,
        // 添加分类表单的数据
        addCateForm: {
          cat_name: '',
          // 父级分类的id  添加的是1级分类的话父id为0
          cat_pid: 0,
          // 分类 ID
          cat_level: 0
        },
        // 添加分类的验证规则
        addCateFormRules: {
          cat_name: [{
            required: true,
            message: '请输入分类的名称',
            trigger: 'blur'
          }],
          cat_level: [{
            required: true,
            message: '请选择分类的等级',
            trigger: 'blur'
          }]

        },
        // 父级分类的数据
        parentCateList: [],
        // cascader的配置对象
        cascaderProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          checkStrictly: true
        },
        // 由于是多级来选所以一定要绑定成数组
        selectedKeys: [],
        // 控制编辑Dialog
        editCateDialogVisible: false,
        // 修改后的分类名称
        editCateForm: {
          cat_name: ''
        }
      }
    },
    methods: {
      //  获取分类数据
      async getCateList() {
        const {
          data: res
        } = await this.$http.get('categories', {
          params: this.queryInfo
        })

        if (res.meta.status !== 200) {
          return this.$message.error('获取商品分类失败')
        }
        console.log(res.data)
        this.catelist = res.data.result
        this.total = res.data.total
      },
      // 监听pagesize的改变
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getCateList()
      },
      // 当前页码值pagenow的改变
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getCateList()
      },
      // 点击按钮显示添加分类的Dialog
      async showAddCateDialog() {
        // console.log(await this.getParentCateList())
        this.parentCateList = await this.getParentCateList().then(result => {
          return result
        })
        this.addCateDialogVisible = true
      },
      // 获取父级分类的数据列表
      async getParentCateList() {
        const {
          data: res
        } = await this.$http.get('categories', {
          params: {
            type: 2
          }
        })

        if (res.meta.status !== 200) {
          return this.$message.error('获取父级分类数据失败')
        }
        //  console.log(res.data)
        return res.data
      },
      // 监听选择项发生改变
      parentCateChanged() {
        if (this.selectedKeys.length > 0) {
          // 永远选择最后一项当作父分类的id
          this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]

          console.log(this.selectedKeys, this.addCateForm.cat_pid)

          // 为分类 赋予级别
          this.addCateForm.cat_level = this.selectedKeys.length
          return false
        } else {
          this.addCateForm.cat_level = 0
          this.addCateForm.cat_pid = 0
        }
      },
      // 点击按钮 添加分类
      async addCate() {
        //  console.log(this.addCateForm)
        this.$refs.addCateFormRef.validate(isRight => {
          if (!isRight) {
            return this.$message.error('添加分类失败')
          }
        })
        const {
          data: res
        } = await this.$http({
          method: 'post',
          url: 'categories',
          data: this.addCateForm
        })

        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error(`添加分类失败${',' + res.meta.msg}!`)
        }
        this.getCateList()
        this.addCateDialogVisible = false
        this.$message.success(res.meta.msg)
      },
      // 监听分类添加Dialog对话框的关闭事件
      addCateDialogClosed() {
        // console.log(this.addCateForm)
        this.$refs.addCateFormRef.resetFields()
        // 重置级联数据
        this.selectedKeys = []
        this.addCateForm.cat_level = 0
        this.addCateForm.cat_pid = 0
      },
      // 监听点击删除按扭
      async removeCate(cateInfo) {
        // console.log(cateInfo)
        const confirmResult = await this.$confirm('此操作将永久删除该商品分类及分类下的子类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => {
          return error
        })
        if (confirmResult !== 'confirm') {
          return this.$message({
            type: 'info',
            message: '取消删除商品分类',
            duration: 1500
          })
        }
        const {
          data: res
        } = await this.$http.delete(`categories/${cateInfo.cat_id}`)
        //  console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error(`删除商品分类失败${',' + res.meta.msg} !`)
        }
        this.getCateList()
        this.$message.success('删除成功！')
      },
      // 监听修改分类确认按钮
      async editCate() {
        this.$refs.editCateFormRef.validate(isRight => {
          if (!isRight) {
            this.editCateForm.cat_name = ''
            return this.$message.error('信息填写不正确')
          }
        })
        const {
          data: res
        } = await this.$http.put(`categories/${this.editCateForm.cat_id}`, {
          cat_name: this.editCateForm.cat_name
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新分类失败')
        }
        this.getCateList()
        this.editCateDialogVisible = false
        this.$message.success(res.meta.msg)
      },
      // 监听商品分类编辑按钮
      async showEditCateDialog(editInfo) {
        this.editCateDialogVisible = true
        // console.log(editInfo)
        const {
          data: res
        } = await this.$http.get(`categories/${editInfo.cat_id}`)
        if (res.meta.status !== 200) {
          return this.$message.error(`获取最新商品信息失败${',' + res.meta.msg} !`)
        }
        this.editCateForm = res.data
        // console.log(this.editCateForm)
      },
      // 监听商品分类编辑Dialog关闭
      editCateDialogClosed() {
        this.$refs.editCateFormRef.resetFields()
      }
    },
    created() {
      this.getCateList()
    }
  }

</script>

<style lang="less" scoped>
  .treeTable {
    margin-top: 15px;
  }

  .el-cascader {
    width: 100%;
  }

</style>
